<template>
  <BaseDialog
    :visible="visible"
    :title="title"
    width="800px"
    footer-type="close"
    close-text="关闭"
    @update:visible="handleUpdateVisible"
    @close="handleClose"
  >
    <!-- 源节点列表 -->
    <ElementTable
      :data="sourceNodes"
      :tableTitle="tableColumns"
      :showPagination="false"
      :maxHeight="400"
    />
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import BaseDialog from './BaseDialog.vue'
import ElementTable from './ElementTable/index.vue'
import { $getAllSourceNodesByServerId, type SourceNode } from '@/api/nvr'
import { error } from '@/utils/toast'

// Props 定义
interface Props {
  visible: boolean
  title?: string
  serverId?: string
}

const props = withDefaults(defineProps<Props>(), {
  title: '源节点列表',
  serverId: ''
})

// 事件定义
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'close': []
}>()

// 数据
const sourceNodes = ref<SourceNode[]>([])
const loading = ref(false)

// 表格列配置
const tableColumns = ref([
  {
    type: 'text',
    label: 'ID',
    prop: 'sourceId',
    width: '120'
  },
  {
    type: 'text',
    label: '名称',
    prop: 'sourceName',
    width: '150'
  },
  {
    type: 'text',
    label: 'IP地址',
    prop: 'ip',
    width: '120'
  },
  {
    type: 'text',
    label: '端口',
    prop: 'port',
    width: '80'
  },
  {
    type: 'text',
    label: 'UUID',
    prop: 'uuid'
  }
])

// 加载源节点数据
const loadSourceNodes = async () => {
  if (!props.serverId) {
    error('服务器ID不能为空')
    return
  }

  try {
    loading.value = true
    const response = await $getAllSourceNodesByServerId(props.serverId)
    console.log('源节点数据:', response)
    sourceNodes.value = response.data || []
  } catch (err) {
    error('获取源节点数据失败')
    console.error('获取源节点数据失败:', err)
    sourceNodes.value = []
  } finally {
    loading.value = false
  }
}

// 处理 visible 更新
const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

// 处理关闭
const handleClose = () => {
  emit('close')
  emit('update:visible', false)
}

// 监听 visible 变化，当弹框打开时加载数据
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && props.serverId) {
      loadSourceNodes()
    }
  },
  { immediate: true }
)
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>
